<template>
  <div calss="container">
    <h3>nextTick</h3>
    <!-- 1.什么情景下用nextTick，作用是什么，原理是什么 -->
    <!-- 当我需要将一部分逻辑延迟执行的时候,推后执行的时候,就可以使用nextTick -->
    <!-- 因为vue中数据更新是异步的,修改了数据,想要获取数据更新之后的DOM,就可以使用nextTick -->
    <input type="text" ref="searchInput" v-if="showInput" @input="focusInput" />
    <button @click="openSearch">打开</button>
    <div v-for="(v, i) in list" :key="i">{{ v.title }}</div>
    <input type="text" v-model="item.title" />
    <button @click="addList">添加</button>
  </div>
</template>

<script>
import http from "@/utils/request";
export default {
  data() {
    return { showInput: false, list: [], item: { id: "", title: "" } };
  },
  // 计算属性
  computed: {},
  // 方法集合
  methods: {
    getList() {
      if (this.list.length <= 0) {
        http.get("/json/list.json").then((res) => {
          console.log(res.data);
          this.list = res.data;
        });
      } else {
        let addItem = JSON.parse(localStorage.getItem("item"));
        if (addItem) {
          let index = 0;
          let flag = this.list.some((v, i) => {
            index = i;
            return v.id == addItem.id;
          });
          if (flag) {
            this.list[index].title = addItem.title;
          } else {
            this.list.push(addItem);
          }
        }
      }
    },

    addList() {
      if (this.item) {
        this.item.id = new Date().getTime();
      }
      localStorage.setItem("item", JSON.stringify(this.item));
    },
    openSearch() {
      this.showInput = !this.showInput;
      this.$nextTick(() => {
        this.$refs.searchInput.focus();
        this.getList();
      });
    },
    focusInput() {},
  },
  // 生命周期 - DOM元素渲染前调用
  created() {
    this.getList();
  },
  // 生命周期 - DOM元素渲染后调用
  mounted() {},
  updated() {
    this.getList();
  },
  components: {},
};
</script>
<style lang='less' scoped>
.container {
  width: 100vw;
  margin: 0 auto;
}
input {
  padding-left: 5px;
}
</style>
